package vn.info.vietnaminfo.db;

import java.util.ArrayList;
import java.util.List;

import vn.info.vietnaminfo.data.DSLoaiHinhKD;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class DaoLoaiHinhKD extends BaseDao
{
	public static final String TABLE_NAME 	= "LOAI_HINH_KD";
	private static final String ID_KD 		= "ID";
    private static final String MA_LOAI_KD 	= "MA_LOAI_KD";
    private static final String TEN_LOAI_KD = "TEN_LOAI_KD";    
    public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + ID_KD + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MA_LOAI_KD + " TEXT, " + TEN_LOAI_KD + " TEXT)";
    private static final String[] COLUMNS 	= { ID_KD, MA_LOAI_KD, TEN_LOAI_KD };
	
	public DaoLoaiHinhKD(Context context)
	{
		super(context);
	}
	
	private DSLoaiHinhKD getParamSetDto(Cursor cursor)
	{
		int index = 1;
		DSLoaiHinhKD dto = new DSLoaiHinhKD(cursor.getString(index++), cursor.getString(index++));
        return dto;
    }
	
	//Lấy toàn bộ thông tin có trong table
	public List<DSLoaiHinhKD> findAll()
	{
        List<DSLoaiHinhKD> list = new ArrayList<DSLoaiHinhKD>();
        Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
        while (cursor.moveToNext())
        {
            list.add(getParamSetDto(cursor));
        }
        if (cursor != null)
        {
            cursor.close();
        }
        return list;
    }
	
	//Kiểm tra sự tồn tại của loại hình kinh doanh
	public DSLoaiHinhKD findById(String maloaikd)
	{
        String selection = MA_LOAI_KD + " = '" + maloaikd + "'";
        Cursor cursor = db.query(TABLE_NAME, COLUMNS, selection, null, null, null, null);
        try
        {
            if (cursor.moveToNext()) { return getParamSetDto(cursor); }
        }
        finally
        {
            if (cursor != null) { cursor.close(); }
        }
        return null;
    }
	
	//Lưu thông tin loại hình kinh doanh
	public long insert(String maloaikd, String tenloaikd)
	{
		if(findById(maloaikd) == null)
		{
			ContentValues values = new ContentValues();
	        values.put(MA_LOAI_KD, maloaikd);
	        values.put(TEN_LOAI_KD, tenloaikd);
	        return db.insert(TABLE_NAME, null, values);
		}
		return -1;
    }
}